package com.learning.thread.optimize;

/**
 * ClassName: DeadLock
 * Description: 简单死锁的例子
 * Date: 2018/7/17 10:22 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class DeadLock {

    public static String obj1 = "obj1";
    public static String obj2 = "obj2";

    public static void main(String[] args) {
        Thread a = new Thread(new Lock1(), "Thread_Lock_1");
        Thread b = new Thread(new Lock2(), "Thread_Lock_2");
        a.start();
        b.start();
    }

    static class Lock1 implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("Lock1 running");
                while (true) {
                    synchronized (DeadLock.obj1) {
                        System.out.println("Lock1 lock obj1");
                        //获取obj1后先等一会儿，让Lock2有足够的时间锁住obj2
                        Thread.sleep(3000);
                        synchronized (DeadLock.obj2) {
                            System.out.println("Lock1 lock obj2");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class Lock2 implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("Lock2 running");
                while (true) {
                    synchronized (DeadLock.obj2) {
                        System.out.println("Lock2 lock obj2");
                        Thread.sleep(3000);
                        synchronized (DeadLock.obj1) {
                            System.out.println("Lock2 lock obj1");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
/*
* dump 输出：
"Thread_Lock_2":
	at com.learning.thread.optimize.DeadLock$Lock2.run(DeadLock.java:54)
	- waiting to lock <0x0000000780954668> (a java.lang.String)
	- locked <0x0000000780954698> (a java.lang.String)
	at java.lang.Thread.run(Thread.java:745)
"Thread_Lock_1":
	at com.learning.thread.optimize.DeadLock$Lock1.run(DeadLock.java:34)
	- waiting to lock <0x0000000780954698> (a java.lang.String)
	- locked <0x0000000780954668> (a java.lang.String)
	at java.lang.Thread.run(Thread.java:745)
* */